<?php

namespace App\Console\Commands\Movie;

use App\Console\Commands\Elasticsearch\Indices\ProjectIndex;
use App\Models\Image;
use App\Models\Movie;
use Illuminate\Console\Command;
use GuzzleHttp\Client;
use Illuminate\Support\Str;
use GuzzleHttp\Exception\RequestException;
class GetImage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'movie:get-image
                            {--id=0 : 抓取指定 ID 的电影封面}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取电影的图片';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle(Client $http)
    {
        $id = $this->option('id');
        if ($id > 0) {
            if (!$movie = Movie::where('douban_id', $id)->first()) {
                $this->info('电影不存在');
            } else if(Str::contains($movie->cover, 'movie_default_large.png')) {
                $this->info('没有封面');
            } else {
                $this->getOne($movie, $http);
            }
        } else {
            Movie::query()
                ->where('cover', 'not like', '%movie_default_large.png')
                ->doesntHave('cover_image')
                ->chunk(100, function($movies) use ($http) {
                    $this->info(sprintf('正在处理第%s到第%s个电影', $movies->first()->id, $movies->last()->id));
                    foreach($movies as $movie) {
                        $this->getOne($movie, $http);
                    }
                });
        }
    }
    protected function getOne(Movie $movie, Client $http)
    {
        list('basename' => $filename) = pathinfo($movie->cover);
        try {
            $http->get('https://doubanqaq.oss-cn-shenzhen.aliyuncs.com/' . $filename);
            $data = [
                'user_id' => 0,
                'type'  => 'movie_cover',
                'movie_id' => $movie->id,
                'path' => $filename,
            ];
            Image::create($data);
            $this->info('完成电影 ' . $movie->name . ' 封面的下载');
        } catch(RequestException $e) {

        }
    }
}
